package com.tfblog.blog.interceptor;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.tfblog.blog.annotation.PassToken;
import com.tfblog.blog.annotation.UserLoginToken;
import com.tfblog.blog.entity.User;
import com.tfblog.blog.service.UserService;
import lombok.experimental.PackagePrivate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * Created by FengBin on 2021/5/7 14:19
 * 自定义拦截器 : 对用户登录进行拦截,token验证
 */
public class AuthenticationInterceptor implements HandlerInterceptor {


    @Autowired
    UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取token ===> 将token信息设置在请求头里,一直报'options错误',我们选择使用将token令牌作为请求参数保存起来
        if (request.getMethod().equals("OPTIONS")) {
            response.setStatus(HttpServletResponse.SC_OK);
            return true;
        }
        //获取请求体里的token令牌信息
        //String token = request.getParameter("Authorization");
        String token = request.getHeader("Authorization");
        //如果不是映射到方法,则直接通过
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //检测是否存在passToken注解,有的话则直接跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        //检测有没有需要用户权限的注解
        if (method.isAnnotationPresent(UserLoginToken.class)) {
            UserLoginToken userLoginToken = method.getAnnotation(UserLoginToken.class);
            if (userLoginToken.required()) {
                //我们选择执行认证
                if (token == null) {
                    //说明请求头中不存在token令牌
                    throw new RuntimeException("未携带token,请重新登录");
                }
                //获取token中的用户名
                String username;
                try {
                    username = JWT.decode(token).getAudience().get(0);
                }catch (JWTDecodeException j) {
                    //未认证授权异常
                    throw new RuntimeException("401");
                }
                //通过username获取对应的用户
                User user = userService.findByUsername(username);
                if (user == null) {
                    throw new RuntimeException("该用户不存在,请重新登录...");
                }
                //继续验证token
                JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();
                try {
                    jwtVerifier.verify(token);
                }catch (JWTVerificationException e) {
                    //tokenn认证失败
                    throw new RuntimeException("401");
                }
                return true;
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
